<?php

/**
 * Capital Direct Lending (http://www.philbsd.com/cdl)
 *
 * Copyright (C) 2008 Philippine Business Solution Developers <http://www.philbsd.com>
 * All rights reserved.
 *
 *
 * LICENSE
 *
 * This source file is subject to the GNU General Public License v3 license
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.gnu.org/licenses/gpl-3.0.txt
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@philbsd.com so we can send you a copy immediately.
 *
 * @copyright  (c) 2008 Philippine Business Solution Developers. (http://www.philbsd.com)
 * @license    http://www.gnu.org/licenses/gpl-3.0.txt
 * @version    $Id: borrower.php 243 2008-05-01 16:37:25Z jundie2000 $
 */

if (!defined('BASEPATH')) exit('No direct script access allowed');

class Borrower extends SB_Controller
{
	public function __construct()
	{
		parent::__construct();
		$this->_data['menuLoan'] = true;
        $this->load->model('Loans');
	}

	public function index()
	{
		//$this->input->post();
		//$this->load->library('calendar');
		//echo $this->calendar->generate();
		$this->render('borrower/index.shtml');
	}

	public function popsearch($page_name = 'borrower', $q = '')
	{
		$this->_data['page_name'] = $page_name;
		$this->_data['q'] = $q;
		if ($q == '') { // search all
		} else {
			$sql = "SELECT * FROM profiles p RIGHT JOIN borrowers b ON b.profile_id = p.id WHERE p.last_name LIKE '%$q%' OR p.first_name LIKE '%$q%' OR p.middle_name LIKE '%q%' OR p.address LIKE '%$q%' OR p.barangay LIKE '%$q%' OR p.city LIKE '%%q%' OR p.island LIKE '%$q%'";
			$result = $this->db->query($sql);
			if ($result->num_rows() > 0) {
				$this->_data['records'] = array();
				foreach ($result->result_array() as $row) {
					$this->_data['records'][] = $row;
                                }
			}
		}

		$this->render('borrower/popsearch.shtml', array(), 'popup.shtml');
	}

	public function search()
	{
		$this->render('borrower/search.shtml');
	}

	public function view($id)
	{
		$this->_data['record'] = $this->Loans->getBorrower($id);
		$this->render('borrower/view.shtml');
	}
    public function edit($id)
	{
		$this->_data['record'] = $this->Loans->getBorrower($id);
		$this->render('borrower/edit.shtml');
        print_r($_POST);
        // editting borrower
        if (isset($_POST['Profile/last_name'])) {

            $this->db->trans_begin();
		    $data = $this->_swordPost['Profile'];
			$this->db->where('id', $_POST['Profile/id']);
            $this->db->update('profiles', $data);
            $data = $this->_swordPost['Borrower'];
			$this->db->where('id', $_POST['Borrower/id']);
           	$this->db->update('borrowers', $data);
       		$this->db->trans_commit();

            $failedUpload = false;
            $borrowerPhotoDir = PHOTO_DIR . DS . 'borrowers';
            $uploadConfig['allowed_types'] = 'gif|jpg|png';
            $uploadConfig['max_size']       = '10240';
            $uploadConfig['max_width']  = '4000';
            $uploadConfig['max_height']  = '4000';
            $this->load->library('upload');

            $imgConfig['create_thumb'] = TRUE;
            $imgConfig['maintain_ratio'] = TRUE;
            $imgConfig['width'] = 200;
            $imgConfig['height'] = 200;
            $this->load->library('image_lib');

            // uploading borrower's photo if exists
            if (isset($_FILES['borrower_photo']['name'])) {
				$photoExt = pathinfo($_FILES['borrower_photo']['name'], PATHINFO_EXTENSION);
            	$borrowerPhotoDestination = $borrowerPhotoDir . DS . "{$data['id']}.{$photoExt}";
            	$borrowerPhotoThumbDestination = $borrowerPhotoDir . DS . "{$data['id']}_thumb.{$photoExt}";

            	if (isset($borrowerPhotoDestination)) {
            		$this->_unlinkIfExists($borrowerPhotoDestination);
            	}
            	if (isset($borrowerPhotoThumbDestination)) {
            		$this->_unlinkIfExists($borrowerPhotoThumbDestination);
            	}

            	$uploadConfig['upload_path'] = $borrowerPhotoDir . DS;
                $this->upload->initialize($uploadConfig);
                if (!$this->upload->do_upload('borrower_photo')) {
                	$failedUpload = true;
                    $errMsg = "\n<br />Failed to upload borrower's photo. " . $this->upload->display_errors('', '');
                    if (isset($this->_data['msg'])) {
                    	$this->_data['msg'] .= $errMsg;
                    } else {
                        $this->_data['msg'] = $errMsg;
                    }
                } else {
                    @rename($uploadConfig['upload_path'] . $_FILES['borrower_photo']['name'], $borrowerPhotoDestination);
                    $imgConfig['source_image'] = $borrowerPhotoDestination;
                    $this->image_lib->initialize($imgConfig);
                    if (!$this->image_lib->resize()) {
                    	$failedUpload = true;
                        $errMsg = "\n<br />{$imgConfig['source_image']}Failed to resize borrowers's photo. " . $this->image_lib->display_errors('', '');
                        if (isset($this->_data['msg'])) {
                        	$this->_data['msg'] .= "\n<br />{$errMsg}";
                        } else {
                            $this->_data['msg'] = $errMsg;
                        }
                    }
					$data['photo_ext'] = $photoExt;
                }
            }


            $this->session->set_flashdata('msg', "Successfully saved!");
            header("Location: {$this->_data['baseUrl']}/borrower/view/{$_POST['loan_id']}.html");
			exit;
        }
	}
    public function cb_view($id)
	{
		$this->_data['record'] = $this->Loans->getCoBorrower($id);
		$this->render('borrower/cb_view.shtml');
	}
    public function edit_cb($id)
	{
		$this->_data['record'] = $this->Loans->getCoBorrower($id);
		$this->render('borrower/edit_cb.shtml');

        // editting borrower
        if (isset($_POST['Profile/last_name'])) {
           	$this->db->trans_begin();
		    $data = $this->_swordPost['Profile'];
			$this->db->where('id', $_POST['Profile/id']);
            $this->db->update('profiles', $data);
             $data = $this->_swordPost['Borrower'];
			$this->db->where('id', $_POST['Borrower/id']);
           	$this->db->update('borrowers', $data);
            $this->db->trans_commit();

            $failedUpload = false;
            $borrowerPhotoDir = PHOTO_DIR . DS . 'borrowers';
            $uploadConfig['allowed_types'] = 'gif|jpg|png';
            $uploadConfig['max_size']       = '10240';
            $uploadConfig['max_width']  = '4000';
            $uploadConfig['max_height']  = '4000';
            $this->load->library('upload');

            $imgConfig['create_thumb'] = TRUE;
            $imgConfig['maintain_ratio'] = TRUE;
            $imgConfig['width'] = 200;
            $imgConfig['height'] = 200;
            $this->load->library('image_lib');

            // uploading borrower's photo if exists
            if (isset($_FILES['borrower_photo']['name'])) {
				$photoExt = pathinfo($_FILES['borrower_photo']['name'], PATHINFO_EXTENSION);
            	$borrowerPhotoDestination = $borrowerPhotoDir . DS . "{$data['id']}.{$photoExt}";
            	$borrowerPhotoThumbDestination = $borrowerPhotoDir . DS . "{$data['id']}_thumb.{$photoExt}";

            	if (isset($borrowerPhotoDestination)) {
            		$this->_unlinkIfExists($borrowerPhotoDestination);
            	}
            	if (isset($borrowerPhotoThumbDestination)) {
            		$this->_unlinkIfExists($borrowerPhotoThumbDestination);
            	}

            	$uploadConfig['upload_path'] = $borrowerPhotoDir . DS;
                $this->upload->initialize($uploadConfig);
                if (!$this->upload->do_upload('borrower_photo')) {
                	$failedUpload = true;
                    $errMsg = "\n<br />Failed to upload borrower's photo. " . $this->upload->display_errors('', '');
                    if (isset($this->_data['msg'])) {
                    	$this->_data['msg'] .= $errMsg;
                    } else {
                        $this->_data['msg'] = $errMsg;
                    }
                } else {
                    @rename($uploadConfig['upload_path'] . $_FILES['borrower_photo']['name'], $borrowerPhotoDestination);
                    $imgConfig['source_image'] = $borrowerPhotoDestination;
                    $this->image_lib->initialize($imgConfig);
                    if (!$this->image_lib->resize()) {
                    	$failedUpload = true;
                        $errMsg = "\n<br />{$imgConfig['source_image']}Failed to resize borrowers's photo. " . $this->image_lib->display_errors('', '');
                        if (isset($this->_data['msg'])) {
                        	$this->_data['msg'] .= "\n<br />{$errMsg}";
                        } else {
                            $this->_data['msg'] = $errMsg;
                        }
                    }
					$data['photo_ext'] = $photoExt;
                }
            }


            $this->session->set_flashdata('msg', "Successfully saved!");
            header("Location: {$this->_data['baseUrl']}/borrower/cb_view/{$_POST['loan_id']}.html");
			exit;
        }
	}

	public function popadd($page_name = 'borrower')
	{
		$this->_data['page_name'] = $page_name;

		if ($this->input->post('page_name')) {
			$this->_data['page_name'] = $this->input->post('page_name');
		}
                $this->load->helper(array('form', 'url'));
                $this->load->library('validation');

                if (isset($_POST['Profile/last_name'])) {

                        $failedUpload = false;
                        $borrowerPhotoDir = PHOTO_DIR . DS . 'borrowers';

                        $uploadConfig['allowed_types'] = 'gif|jpg|png';
                        $uploadConfig['max_size']       = '10240';
                        $uploadConfig['max_width']  = '4000';
                        $uploadConfig['max_height']  = '4000';
                        $this->load->library('upload');

                        $imgConfig['create_thumb'] = TRUE;
                        $imgConfig['maintain_ratio'] = TRUE;
                        $imgConfig['width'] = 200;
                        $imgConfig['height'] = 200;   
                        $this->load->library('image_lib');

                        $rules['Profile/last_name'] = "required";
                        $rules['Profile/first_name'] = "required";
                        $rules['Profile/address'] = "required";
                        $rules['Profile/barangay'] = "required";
                        $rules['Profile/city'] = "required";
                        $rules['Profile/island'] = "required";
                        $rules['Profile/phone'] = "required";
                        $rules['Profile/birthdate'] = "required";
                        $rules['Profile/gender'] = "required";
                        $rules['Profile/civil_status'] = "required";
                        $this->validation->set_rules($rules);

                        $fields['Profile/last_name'] = "Last Name";
                        $fields['Profile/first_name'] = "First Name";
                        $fields['Profile/address'] = "Address";
                        $fields['Profile/barangay'] = "Barangay";
                        $fields['Profile/city'] = "City";
                        $fields['Profile/island'] = "Island";
                        $fields['Profile/phone'] = "Phone";
                        $fields['Profile/birthdate'] = "Birthdate";
                        $fields['Profile/gender'] = "Gender";
                        $fields['Profile/civil_status'] = "Civil Status";
                        $this->validation->set_fields($fields);

                        if ($this->validation->run()) {
                                $this->db->trans_begin();

                                // adding profile for borrower
                                $data = $this->_swordPost['Profile'];
                                $this->db->insert('profiles', $data);
                                $profileId = $this->db->insert_id();

                                // adding borrower
                                $data = array(
                                                'profile_id' => $profileId,
                                                'status_date' => time(),
                                                );
                                $yr = date('Y');
                                $borrowerId = "{$yr}-0001";
                                $sql = "SELECT `id` FROM borrowers WHERE `id` LIKE '{$yr}-%' ORDER BY `id` DESC LIMIT 0, 1";
                                $result = $this->db->query($sql);
                                if ($result->num_rows() > 0) {
                                        $row = $result->row();
                                        $x = explode('-', $row->id);
                                        $tmpId = (int) $x[1] + 1;
                                        $tmpId = str_pad($tmpId, 4, '0', STR_PAD_LEFT);
                                        $borrowerId = "{$yr}-{$tmpId}";
                                }
                                $data['id'] = $borrowerId;
								$data['status_date'] = date("Y-m-d");

                                // uploading borrower's photo if exists
                                if (isset($_FILES['borrower_photo']['name'])) {
                                        $uploadConfig['upload_path'] = $borrowerPhotoDir . DS;
                                        $this->upload->initialize($uploadConfig);
                                        if (!$this->upload->do_upload('borrower_photo')) {
                                                $failedUpload = true;
                                                $errMsg = "\n<br />Failed to upload borrower's photo. " . $this->upload->display_errors('', '');
                                                if (isset($this->_data['msg'])) {
                                                        $this->_data['msg'] .= $errMsg;
                                                } else {

                                                        $this->_data['msg'] = $errMsg;
                                                }
                                        } else {
                                                $photoExt = pathinfo($_FILES['borrower_photo']['name'], PATHINFO_EXTENSION);
                                                $borrowerPhotoDestination = $borrowerPhotoDir . DS . "{$borrowerId}.{$photoExt}";
                                                $borrowerPhotoThumbDestination = $borrowerPhotoDir . DS . "{$borrowerId}_thumb.{$photoExt}";
                                                @rename($uploadConfig['upload_path'] . $_FILES['borrower_photo']['name'], $borrowerPhotoDestination);
                                                $imgConfig['source_image'] = $borrowerPhotoDestination;
                                                $this->image_lib->initialize($imgConfig);
                                                if (!$this->image_lib->resize()) {
                                                        $failedUpload = true;
                                                        $errMsg = "\n<br />{$imgConfig['source_image']}Failed to resize borrowers's photo. " . $this->image_lib->display_errors('', '');
                                                        if (isset($this->_data['msg'])) {
                                                                $this->_data['msg'] .= "\n<br />{$errMsg}";
                                                        } else {
                                                                $this->_data['msg'] = $errMsg;
                                                        }
                                                }
												$data['photo_ext'] = $photoExt;
                                        }
                                }
                                $this->db->insert('borrowers', $data);


                                if ($this->db->trans_status() === FALSE || $failedUpload) {
                                        if (isset($borrowerPhotoDestination)) {
                                                $this->_unlinkIfExists($borrowerPhotoDestination);
                                        }
                                        if (isset($borrowerPhotoThumbDestination)) {
                                                $this->_unlinkIfExists($borrowerPhotoThumbDestination);
                                        }

                                        $this->db->trans_rollback();
                                        $errMsg = "Failed to add!";
                                        if (isset($this->_data['msg'])) {
                                                $this->_data['msg'] .= $errMsg;
                                        } else {
                                                $this->_data['msg'] = $errMsg;
                                        }
                                } else {
                                        $this->db->trans_commit();
										$this->_data['success_msg'] = "Successfully saved.";
									$this->_data['my_id'] = $borrowerId;
                                }

			}
		}

		$this->render('borrower/popadd.shtml', array(), 'popup.shtml');
	}

}
